package cn.jee.jsp;

import cn.jee.jsp.util.JdbcUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.hsqldb.jdbc.JDBCClob;

import java.io.IOException;
import java.nio.file.Paths;

@MultipartConfig(maxFileSize = 1024*1024)
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Part part=req.getPart("photo");
    System.out.println(part);
    String contentType=part.getContentType();
    //判断一下，contentType.startsWith("image")
    String oldName=part.getSubmittedFileName();
    String realPath=req.getServletContext().getRealPath("/uploads");
    String destFile=Paths.get(realPath,oldName).toString();
    System.out.println(destFile);
    part.write(destFile);
    HttpSession session=req.getSession();
    //建立图片和学生之间的关系 update stu set photo=? where id=?
    String id=req.getParameter("id");
    String sql="update stu set photo=? where id=?";
    int row=JdbcUtil.update(sql,new Object[]{oldName,id});
    session.setAttribute("stu_msg",row>0?"上传成功":"上传失败");
    session.setAttribute("contentType",contentType);
    session.setAttribute("fileName",oldName);
    resp.sendRedirect(req.getContextPath()+"/stu/upload_res.jsp");
  }
}
